package com.wlw.admin.openeye.ui.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.util.Pair
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import cn.bingoogolapple.bgabanner.BGABanner
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.hazz.kotlinmvp.view.recyclerview.ViewHolder
import com.hazz.kotlinmvp.view.recyclerview.adapter.CommonAdapter
import com.wlw.admin.openeye.Constants
import com.wlw.admin.openeye.R
import com.wlw.admin.openeye.durationFormat
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.ui.activity.VideoDetailActivity
import io.reactivex.Observable

class HomeAdapter(context: Context, data: ArrayList<HomeBean.Issue.Item>) : CommonAdapter<HomeBean.Issue.Item>(context, data, -1) {


    var bannerItemSize = 0

    companion object {
        private const val ITEM_TYPE_BANNER = 1
        private const val ITEM_TYPE_TEXT_HEADER = 2
        private const val ITEM_TYPE_CONTENT = 3
    }

    fun setBannerSize(count: Int) {
        bannerItemSize = count
    }

    fun addItemData(itemList: ArrayList<HomeBean.Issue.Item>) {
        mData.addAll(itemList)
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {

        return when {
            position == 0 -> ITEM_TYPE_BANNER

            mData[position + bannerItemSize - 1].type == "textHeader" -> ITEM_TYPE_TEXT_HEADER

            else -> ITEM_TYPE_CONTENT
        }
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
        return when (p1) {
            ITEM_TYPE_BANNER -> ViewHolder(inflateView(R.layout.item_home_banner, p0))
            ITEM_TYPE_TEXT_HEADER -> ViewHolder(inflateView(R.layout.item_home_header, p0))
            else -> ViewHolder(inflateView(R.layout.item_home_content, p0))
        }
    }

    private fun inflateView(layoutId: Int, parent: ViewGroup): View {
        return LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
    }

    override fun bindData(holder: ViewHolder, data: HomeBean.Issue.Item, position: Int) {
        when (getItemViewType(position)) {
            ITEM_TYPE_BANNER -> {
                onBindBannerHolder(holder)
            }
            ITEM_TYPE_TEXT_HEADER -> {
                holder.setText(R.id.tvHeader, mData[position + bannerItemSize - 1].data?.text ?: "")
            }
            else -> {
                onBindVideoHolder(holder, mData[position + bannerItemSize - 1])
            }
        }
    }


    override fun getItemCount(): Int {
        return when {
            mData.size > bannerItemSize -> mData.size - bannerItemSize + 1
            mData.isEmpty() -> 0
            else -> 1
        }
    }

    @SuppressLint("SetTextI18n")
    private fun onBindVideoHolder(holder: ViewHolder, item: HomeBean.Issue.Item) {
        val itemData = item.data
        val defAvatar = R.mipmap.default_avatar
        val cover = itemData?.cover?.feed
        var avatar = itemData?.author?.icon
        var tagText = "#"
        if (TextUtils.isEmpty(avatar)) {
            avatar = itemData?.provider?.icon
        }
        Glide.with(mContext)
                .load(cover)
                .transition(DrawableTransitionOptions().crossFade())
                .into(holder.getView(R.id.iv_cover_feed))

        if (avatar.isNullOrEmpty()) {
            Glide.with(mContext)
                    .load(defAvatar)
                    .transition(DrawableTransitionOptions().crossFade())
                    .into(holder.getView(R.id.iv_avatar))
        } else {
            Glide.with(mContext)
                    .load(avatar)
                    .transition(DrawableTransitionOptions().crossFade())
                    .into(holder.getView(R.id.iv_avatar))
        }
        holder.setText(R.id.tv_title, itemData?.title ?: "")
        itemData?.tags?.take(4)?.forEach {
            tagText += (it.name + "/")
        }
        val timeFormat = durationFormat(itemData?.duration)
        tagText += timeFormat

        holder.setText(R.id.tv_tag, tagText)
        holder.setText(R.id.tv_category, "#${itemData?.category}")
        holder.setOnItemClickListener(listener = View.OnClickListener {
            goToVideoPlayer(mContext as Activity, holder.getView(R.id.iv_cover_feed), item)
        })
    }

    private fun onBindBannerHolder(holder: ViewHolder) {
        var bannerItemData = mData.take(bannerItemSize).toCollection(arrayListOf())
        val bannerFeedList = ArrayList<String>()
        val bannerTitleList = ArrayList<String>()
        Observable.fromIterable(bannerItemData).subscribe {
            bannerFeedList.add(it.data?.cover?.feed ?: "")
            bannerTitleList.add(it.data?.title ?: "")
        }
        with(holder) {
            getView<BGABanner>(R.id.banner).run {
                setAutoPlayAble(bannerFeedList.size > 1)
                setData(bannerFeedList, bannerTitleList)
                setAdapter { _, imageView, feedImageUrl, _ ->
                    Glide.with(mContext)
                            .load(feedImageUrl)
                            .transition(DrawableTransitionOptions().crossFade())
                            .into(imageView as ImageView)
                }
            }

            holder.getView<BGABanner>(R.id.banner).setDelegate { _, imageView, _, i ->
                goToVideoPlayer(mContext as Activity, imageView, bannerItemData[i])
            }
        }
    }

    private fun goToVideoPlayer(activity: Activity, imageView: View, item: HomeBean.Issue.Item) {

        val intent = Intent(activity, VideoDetailActivity::class.java)
        intent.putExtra(Constants.BUNDLE_VIDEO_DATA, item)
        intent.putExtra(VideoDetailActivity.TRANSITION, true)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val pair = Pair(imageView, VideoDetailActivity.IMG_TRANSITION)
            val activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, pair)
            ActivityCompat.startActivity(activity, intent, activityOptions.toBundle())
        } else {
            activity.startActivity(intent)
            activity.overridePendingTransition(R.anim.anim_in, R.anim.anim_out)
        }
    }
}

